export class ConversationManager {
  constructor() {
    this.messages = [];
    this.maxMessages = 50; // 最大消息数量，防止上下文过长
  }

  addMessage(role, content, metadata = {}) {
    const message = {
      role,
      content,
      timestamp: new Date().toISOString(),
      ...metadata
    };

    this.messages.push(message);

    // 如果消息太多，移除最早的消息（保留系统消息）
    this.trimMessages();
  }

  getMessages() {
    // 返回标准格式的消息数组
    return this.messages.map(msg => ({
      role: msg.role,
      content: msg.content,
      ...(msg.tool_call_id && { tool_call_id: msg.tool_call_id }),
      ...(msg.tool_calls && { tool_calls: msg.tool_calls })
    }));
  }

  getLastMessage() {
    return this.messages[this.messages.length - 1];
  }

  getMessageCount() {
    return this.messages.length;
  }

  clear() {
    this.messages = [];
  }

  trimMessages() {
    // 保留系统消息，删除过老的对话
    const systemMessages = this.messages.filter(msg => msg.role === 'system');
    const otherMessages = this.messages.filter(msg => msg.role !== 'system');
    this.messages = [...systemMessages, ...otherMessages.slice(-this.maxMessages)];
  }
}